//
//  IdCardController.swift
//  baihuiju
//
//  Created by 赵家彬 on 2018/7/2.
//  Copyright © 2018年 赵家彬. All rights reserved.
//

import UIKit
import RxSwift

class IdCardController: CBBaseViewController {
    
    @IBOutlet weak var tfName: UITextField!
    
    @IBOutlet weak var tfIdcard: UITextField!
    
    @IBOutlet weak var btnConfirm: UIButton!
    
    weak var updateUserInfo:Variable<Bool>?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "身份证号"
        
        tfName.text = MainTools.shared.userModel?.realname
        tfIdcard.text = MainTools.shared.userModel?.idcard
        
        if !(MainTools.shared.userModel?.realname ?? "").isEmpty {
            tfName.isEnabled = false
        }
        
        if !(MainTools.shared.userModel?.idcard ?? "").isEmpty {
            tfIdcard.isEnabled = false
            btnConfirm.isHidden = true
        }
        
        let combineInput = Observable.combineLatest(tfName.rx.text.orEmpty.asObservable(), tfIdcard.rx.text.orEmpty.asObservable()).map { return (name:$0, idcard:$1) }.share(replay:1)
        
        combineInput.map { (input) -> Bool in
            let validateName:Bool = (input.name.count < 10) && (input.name.count > 0)
            let validateIdcard:Bool = input.idcard.count == 15 || input.idcard.count == 18
            return validateIdcard && validateName
            }.subscribe(onNext:{ [unowned self] isValid in
                self.btnConfirm.isEnabled = isValid
                self.btnConfirm.alpha = isValid ? 1.0 : 0.5
            }).disposed(by: disposeBag)
        
        btnConfirm.rx.tap.asObservable()
            .withLatestFrom(combineInput)
            .flatMapLatest { (input) -> Observable<Bool> in
                return NetworkTool.requestData(url: ActionURL.UPDATE_USER_INFO, param: ["uid":MainTools.shared.userModel?.uid ?? "", "idcard":input.idcard, "name":input.name])
                    .map({ (json) -> Bool in
                        return true
                    }).catchErrorJustReturn(false)
            }.subscribe(onNext:{ [unowned self] isSuccess in
                if isSuccess {
                    self.updateUserInfo?.value = true
                    let vwAlert = UIAlertView(title: "提示", message: "保存成功", delegate: nil, cancelButtonTitle: "确定")
                    vwAlert.show()
                    self.navigationController?.popViewController(animated: true)
                }
            }).disposed(by: disposeBag)
    }

}
